/**
 * render pc or mobile page
 */
let renderUtils = module.exports = {};

renderUtils.renderOrJson = function (req, res, next, path, data) {
    if (!req || !res || !path) {
        next(new Error('render error'));
        return;
    }
    // set user info in the data
    data = data || {};
    if (!data.user) {
        if (req.session.user) {
            data.user = req.session.user;
        } else {
            data.user = null;
        }
    }

    data.ua = req.ua;

    if (req.requestType === 'ajax') {
        // ajax request
        res.json(data);
    } else {
        let ejsPath = path;
        let deviceType = renderUtils.deviceType(req);
        if (deviceType === 'mobile') {
            ejsPath = 'mobile/' + ejsPath;
        } else {
            ejsPath = 'pc/' + ejsPath;
        }

        res.render(ejsPath, data);
    }

};
/**
 * get device type
 */
renderUtils.deviceType = function (req) {
    if (!req || !req.ua) {
        return null;
    }
    let result = null;
    if (req.ua.deviceType === 'Personal computer') {
        result = 'pc';
    } else if (req.ua.deviceType === 'Tablet' || req.ua.deviceType === 'Smartphone') {
        result = 'mobile';
    }

    return result;
};

renderUtils.renderNotFound = function (req, res, next, data) {
    let msg;
    if (data && data.errinfo) {
        msg = data.errinfo.uiMsg || data.errinfo.msg;
    }
    if (!msg) {
        msg = 'Sorry..页面没有找到！';
    }

    res.renderByDeviceType(req, res, next, 'notFound', {
        msg: msg
    });
};